<template>
  <div>
    <NavigationComponent />
    <br />
    <div class="student-list-container">
      <span>{{ class_name }}</span>
      <div v-if="students.length">
        <h3>班级学生列表：</h3>
        <ul>
          <li v-for="(student, index) in students" :key="index" class="student-item">
            <img :src="student.image" alt="student image" width="20" height="20" />
            {{ student.name }}
          </li>
        </ul>
      </div>
      <div v-else>
        <h3>没有学生数据</h3>
      </div>
    </div>
  </div>
</template>

<script>
import NavigationComponent from "./NavigationComponent.vue";
import axios from "axios";
import { mapState } from "vuex";
import "@/assets/StudentsList.css";

export default {
  name: "StudentsList",
  components: {
    NavigationComponent,
  },
  data() {
    return {
      class_name: "",
      students: [],
    };
  },
  computed: {
    ...mapState(["selectedDate", "selectedClass"]),
  },
  watch: {
    selectedDate(newDate) {
      console.log("selectedDate 变化:", newDate);
      this.loadStudentData();
    },
    selectedClass(newClass) {
      console.log("selectedClass 变化:", newClass);
      this.class_name = newClass;
      this.loadStudentData();
    },
  },
  mounted() {
    console.log("组件挂载，加载数据");
    this.loadStudentData();

  },
  methods: {
    loadStudentData() {
      if (!this.selectedClass) {
        console.log("没有选定班级");
        return;
      }

      console.log("加载学生数据，班级:", this.selectedClass);

      axios
        .get("/zuowei.json")
        .then((res) => {
          if (res.status === 200) {
            console.log("数据加载成功:", res.data);
            const classData = res.data.find((item) => item.className === this.selectedClass);
            if (classData) {
              this.students = classData.position.map((student) => {
                const name = Object.values(student)[0];
                const image = student.image;
                return { name, image };
              });
              console.log("学生数据加载成功:", this.students);
            } else {
              this.students = [];
              console.log("没有找到匹配的班级数据");
            }
          }
        })
        .catch((error) => {
          console.error("Axios请求失败", error);
        });
    },
  },
};
</script>